

const http = require("http");
const fs = require("fs");
const path = require("path");

const basePath = __dirname;
console.log(__dirname);
const server = http.createServer((request, response) => {
    // response.writeHead(200);
    // response.end("Hello");

    let resourcePath;
    if (request.url === "/")
        resourcePath = path.join(basePath, "index.html");
    else
        resourcePath = path.join(basePath, request.url);


    if (resourcePath.includes(".html?"))
    {
        const index = resourcePath.lastIndexOf("?");
        resourcePath = resourcePath.substring(0, index);
    }

    try {
        const file = fs.readFileSync(resourcePath);
        response.end(file);
    } catch {
        response.setHeader("content-type", "text/html;charset=utf-8");
        response.writeHead(404);
        response.end("404<br>不存在的内容");
    }
    console.log(request.url);
    
});

const port = 3000
console.log(`访问：http://localhost:${port}`);
server.listen(port);




